import {
  Component,
  OnInit, AfterViewInit, OnChanges,
  ViewEncapsulation,
  Input, Output,
  EventEmitter, ElementRef,
  SimpleChanges
} from '@angular/core';

import * as Cropper from 'cropperjs';

@Component({
  selector: 'app-img-cropper',
  templateUrl: './img.cropper.component.html',
  styleUrls: ['./img.cropper.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class ImgCropperComponent implements OnInit, OnChanges {

  private cropper;

  @Input() showModal = true;

  @Input() aspectRatio: number;

  imageUrl = '';
  cropped = null;

  // 声明事件发射器
  @Output() changeObj = new EventEmitter<boolean>();

  // 回传裁剪的图片
  @Output() pictureObj = new EventEmitter<String>();

  constructor(private element: ElementRef) { }

  ngOnInit() {

  }

  ngOnChanges(changes: SimpleChanges): void {
    this.showModal = changes['showModal'].currentValue;
  }

  cancelBox(): void {
    this.showModal = false;
    this.changeObj.emit(false);
  }

  /**
   * 裁剪并将结果返回给上一次父组件
   */
  onCrop(data) {
    this.showModal = false;
    this.changeObj.emit(false);
    this.cropped = data;
    this.pictureObj.emit(this.cropped);
  }

  /**
   * 选择文件后读取，并替换掉之前的图片
   */

  modifyAvatar(event: any) {
    let reader = new FileReader();
    const that = this;
    reader.readAsDataURL(event.target.files[0]);
    reader.onload = function (e) {
      that.imageUrl = this.result;
    };
  }

}
